package net.guerlab.smart.wx.api.autoconfig;

import lombok.AllArgsConstructor;
import net.guerlab.commons.exception.ApplicationException;
import net.guerlab.smart.wx.api.WxMaSubscribeMsgApi;
import net.guerlab.smart.wx.api.feign.FeignWxMaSubscribeMsgApi;
import net.guerlab.smart.wx.core.message.SendMsgResponse;
import net.guerlab.smart.wx.core.message.WxMaSubscribeMessageSendRequest;
import net.guerlab.web.result.Result;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * @author guer
 */
@Configuration
@AutoConfigureAfter(WxMaSubscribeMsgApiLocalServiceAutoConfigure.class)
public class WxMaSubscribeMsgApiFeignAutoConfigure {

    @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
    @Bean
    @ConditionalOnMissingBean(WxMaSubscribeMsgApi.class)
    public WxMaSubscribeMsgApi wxMaSubscribeMsgApiFeignWrapper(FeignWxMaSubscribeMsgApi api) {
        return new WxMaSubscribeMsgApiFeignWrapper(api);
    }

    @AllArgsConstructor
    private static class WxMaSubscribeMsgApiFeignWrapper implements WxMaSubscribeMsgApi {

        private final FeignWxMaSubscribeMsgApi api;

        @Override
        public Map<String, SendMsgResponse> sendMsg(String appId, WxMaSubscribeMessageSendRequest sendData) {
            Result<Map<String, SendMsgResponse>> result = api.sendMsg(appId, sendData);

            if (result.isStatus()) {
                return result.getData();
            }

            throw new ApplicationException(result.getMessage(), result.getErrorCode());
        }
    }

}
